package net.realsee.framework.filter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.realsee.common.enums.wcs.intf.InterfaceClassEnum;
import net.realsee.common.utils.InterfaceUtils;
import net.realsee.domain.wcs.intf.WcsIntf;
import net.realsee.service.wcs.intf.IWcsIntfService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Optional;

/**
 * 外部系统调用之前进行预处理
 *
 * @author 孙正华
 * @since 2023/7/29 13:43
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class PreExternalCallFilter extends OncePerRequestFilter {

    private final IWcsIntfService intfService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 请求的URI
        String requestUri = request.getRequestURI();
        // 查询出所有IN_BOUND接口
        List<WcsIntf> intfList = intfService.listByClass(InterfaceClassEnum.IN_BOUND);
        if (CollUtil.isNotEmpty(intfList)) {
            // 过滤出匹配的那条
            Optional<WcsIntf> optional = intfList.stream()
                .filter(intf -> StrUtil.equalsIgnoreCase(requestUri, intf.getUrl()))
                .findFirst();
            if (optional.isPresent()) {
                InterfaceUtils.calledByHttp(request, response, chain, optional.get());
            } else {
                chain.doFilter(request, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    }
}
